package com.ekuaitu.kuaitustaff.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.ekuaitu.kuaitustaff.R;
import com.ekuaitu.kuaitustaff.adapter.CarReceiveRecordAdapter;
import com.ekuaitu.kuaitustaff.api.ApiService;
import com.ekuaitu.kuaitustaff.api.ApiStore;
import com.ekuaitu.kuaitustaff.api.UrlConstant;
import com.ekuaitu.kuaitustaff.application.MyApplication;
import com.ekuaitu.kuaitustaff.base.BaseActivity;
import com.ekuaitu.kuaitustaff.bean.CarReceiveOrderListBean;
import com.ekuaitu.kuaitustaff.bean.CarTaskStateBean;
import com.ekuaitu.kuaitustaff.utils.AppManager;
import com.ekuaitu.kuaitustaff.utils.Constants;
import com.ekuaitu.kuaitustaff.utils.IntentUtil;
import com.ekuaitu.kuaitustaff.utils.ToastUtils;
import com.ekuaitu.kuaitustaff.utils.ble.BluetoothHelper;
import com.ekuaitu.kuaitustaff.widget.CustomLoadMoreView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class CarReceiveRecordActivity extends BaseActivity implements BaseQuickAdapter.RequestLoadMoreListener, SwipeRefreshLayout.OnRefreshListener {
    @BindView(R.id.rc_personal)
    RecyclerView rcTravel;
    @BindView(R.id.sr_personal)
    SwipeRefreshLayout srPersonal;


    private Context mContext = this;
    private CarReceiveRecordAdapter rechargeRecordAdapter;
    private int curPage = 1;
    private static final int PAGE_SIZE = 10;
    private Intent intent;
    private List<CarTaskStateBean.AttachmentBean> carOrderList = new ArrayList<CarTaskStateBean.AttachmentBean>();

    @Override
    public int getLayoutId() {
        return R.layout.activity_car_receiveorderlist;
    }

    @Override
    public void initView() {

        initAdapter();
        srPersonal.setOnRefreshListener(this);
        srPersonal.setColorSchemeColors(Color.rgb(82, 186, 254));
        rcTravel.setLayoutManager(new LinearLayoutManager(mContext));
        srPersonal.setRefreshing(true);
        onRefresh();

    }

    @Override
    protected void initData() {
    }

    private void initAdapter() {
        rechargeRecordAdapter = new CarReceiveRecordAdapter();
        rechargeRecordAdapter.setOnLoadMoreListener(this, rcTravel);
        rechargeRecordAdapter.setPreLoadNumber(1);
        rechargeRecordAdapter.setLoadMoreView(new CustomLoadMoreView());
        rcTravel.setAdapter(rechargeRecordAdapter);
        rcTravel.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                CarTaskStateBean.AttachmentBean attachmentBean = carOrderList.get(position);
                intent = new Intent();
                intent.putExtra("orderBean", attachmentBean);
                if ("1".equals(attachmentBean.getStaffCarOrderModel().getIsOpenCheck())) {
                    intent.putExtra("actionBean", attachmentBean.getAction());
                }
                setResult(Constants.REQUEST_CAR_RECEIVEDLIST, intent);
                BluetoothHelper.getInstance().removeBleInfo(mContext);//switch
                BluetoothHelper.getInstance().stopScanDevice();
                BluetoothHelper.getInstance().disConnectDevice();
                AppManager.getAppManager().finishActivity();
            }
        });
    }


    @Override
    protected void onResume() {
        super.onResume();
    }


    @Override
    public void onRefresh() {
        curPage = 1;
        rechargeRecordAdapter.setEnableLoadMore(false);//这里的作用是防止下拉刷新的时候还可以上拉加载
        new ApiStore().getRetrofit(UrlConstant.Request.BASE_URL_NEW, "", "").create(ApiService.class).getReceiveOrderList(((MyApplication) getApplication()).getRequestFieldMap(), "1", curPage + "", PAGE_SIZE + "").enqueue(new Callback<CarReceiveOrderListBean>() {
            @Override
            public void onResponse(Call<CarReceiveOrderListBean> call, Response<CarReceiveOrderListBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getErrCode() == 0) {
                        if (null != response.body().getAttachment() && null != response.body().getAttachment().getCarOrderList() && !response.body().getAttachment().getCarOrderList().isEmpty()) {
                            setData(true, response.body().getAttachment().getCarOrderList());
                        }
                        if (srPersonal != null) {
                            rechargeRecordAdapter.setEnableLoadMore(true);
                            srPersonal.setRefreshing(false);
                        }
                    } else if (response.body().getErrCode() == 11) {
                        ToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_SHORT).show();
                        IntentUtil.toLoginActivity(mContext);
                        AppManager.getAppManager().finishAllActivity();
                    } else {
                        rechargeRecordAdapter.setEnableLoadMore(true);
                        srPersonal.setRefreshing(false);
                    }
                }
            }

            @Override
            public void onFailure(Call<CarReceiveOrderListBean> call, Throwable t) {
                if (srPersonal != null) {
                    rechargeRecordAdapter.setEnableLoadMore(true);
                    srPersonal.setRefreshing(false);
                }
                Log.i("neterror", "进行中列表" + t.toString());
                ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onLoadMoreRequested() {
        new ApiStore().getRetrofit(UrlConstant.Request.BASE_URL_NEW, "", "").create(ApiService.class).getReceiveOrderList(((MyApplication) getApplication()).getRequestFieldMap(), "1", curPage + "", PAGE_SIZE + "").enqueue(new Callback<CarReceiveOrderListBean>() {
            @Override
            public void onResponse(Call<CarReceiveOrderListBean> call, Response<CarReceiveOrderListBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getErrCode() == 0) {
                        if (null != response.body().getAttachment() && null != response.body().getAttachment().getCarOrderList() && !response.body().getAttachment().getCarOrderList().isEmpty()) {
                            setData(false, response.body().getAttachment().getCarOrderList());
                        }
                    } else if (response.body().getErrCode() == 11) {
                        ToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_SHORT).show();
                        IntentUtil.toLoginActivity(mContext);
                        AppManager.getAppManager().finishAllActivity();
                    } else {
                        rechargeRecordAdapter.setEnableLoadMore(true);
                        srPersonal.setRefreshing(false);
                    }
                }
            }

            @Override
            public void onFailure(Call<CarReceiveOrderListBean> call, Throwable t) {
                rechargeRecordAdapter.loadMoreFail();
                Log.i("neterror", "进行中列表" + t.toString());
                ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
            }
        });
    }


    private void setData(boolean isRefresh, List data) {
        curPage++;
        final int size = data == null ? 0 : data.size();
        if (isRefresh) {
            carOrderList.clear();
            carOrderList.addAll(data);
            rechargeRecordAdapter.setNewData(data);
        } else {
            if (size > 0) {
                carOrderList.addAll(data);
                rechargeRecordAdapter.addData(data);
            }
        }

        if (size < PAGE_SIZE) {
            //第一页如果不够一页就不显示没有更多数据布局
            rechargeRecordAdapter.loadMoreEnd(isRefresh);
        } else {
            rechargeRecordAdapter.loadMoreComplete();
        }
    }

    @OnClick({R.id.title_back})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                AppManager.getAppManager().finishActivity();
                break;
        }
    }
}

